using System.Diagnostics;
using DimensionsHelper.LanguageService.Syntax;

namespace DimensionsHelper.LanguageService;

public class AnalysisOnErrorStatement : AnalysisStatement
{
    internal AnalysisOnErrorStatement(OnErrorStatement syntaxNode, AnalysisNode? parent) :
        base(AnalysisBoundKinds.OnErrorStatement, syntaxNode, parent)
    {
        Syntax = syntaxNode;
    }
    
    public override OnErrorStatement Syntax { get; }

    public AnalysisGotoStatement? GotoStatement { get; private set; }

    public AnalysisResumeStatement? ResumeStatement { get; private set; }

    public override int ChildrenCount => GotoStatement != null || ResumeStatement != null ? 1 : 0;

    internal override void AddChild(AnalysisNode child)
    {
        Debug.Assert(GotoStatement == null && ResumeStatement == null);
        Debug.Assert(child.BoundKind is AnalysisBoundKinds.GotoStatement or AnalysisBoundKinds.ResumeStatement);

        if (child.BoundKind == AnalysisBoundKinds.GotoStatement)
        {
            GotoStatement = (AnalysisGotoStatement)child;
        }
        else
        {
            ResumeStatement = (AnalysisResumeStatement)child;
        }

        child.Parent = this;
    }

    public override IEnumerable<AnalysisNode> GetChildren()
    {
        if (GotoStatement != null)
        {
            return [GotoStatement];
        }

        if (ResumeStatement != null)
        {
            return [ResumeStatement];
        }

        return [];
    }
}


public static partial class AnalysisNodeFactory
{
    /// <summary>
    /// 创建一个On Error语句
    /// </summary>
    /// <param name="syntaxNode">原始语法节点</param>
    /// <param name="parent">父节点，可以忽略</param>
    public static AnalysisOnErrorStatement OnErrorStatement(OnErrorStatement syntaxNode, AnalysisNode? parent)
    {
        return new AnalysisOnErrorStatement(syntaxNode, parent);
    }
}